﻿using System;
using System.Diagnostics;
using System.Web.Mvc;
using System.Web.Security;
using ViewModel;

namespace MvcEngine.Areas.Profile.Controllers
{
    public class UpdateController : Controller
    {
        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            bool changePasswordSucceeded;
            try
            {
                var currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
                Debug.Assert(currentUser != null, "currentUser != null");
                changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
            }
            catch (Exception)
            {
                changePasswordSucceeded = false;
            }

            if (!changePasswordSucceeded)
            {
                ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                return View(model);
            }

            return RedirectToAction("ChangePasswordSuccess");
        }

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }
    }
}
